package com.newgrand.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.newgrand.domain.model.I8ReturnModel;
import com.newgrand.domain.model.RequestResult;
import com.newgrand.domain.model.StatAmount;
import com.newgrand.service.StatAmountService;
import com.newgrand.utils.*;
import com.newgrand.utils.i8util.I8Converter;
import com.newgrand.utils.i8util.I8Request;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @创建人：ZhaoFengjie
 * @修改人：ZhaoFengjie
 * @创建时间：18:42 2022/10/17
 * @修改时间:：18:42 2022/10/17
 */
@Service
public class StatAmountImpl extends GetPhIdHelper implements StatAmountService {

    private static final String accessId = "zO0IBGSR2vAzY5O3m41G";
    private static final String secretKey = "M5aXXPJBPIr2dDhLVjNfmNXKjbQj4A4dD84P23asu";
    private static final String baseUrl = "https://api.mctech.vip";
    private static OpenApiClient client = new OpenApiClient(baseUrl, accessId, secretKey);
    private static final String pcrApi = "/pp/stat-amount?offset=%s&limit=%s&version=%s&orgId=%s&year=%s&month=%s";
    private static Logger logger = LogManager.getLogger("logger");
    private static NGLog ngLog = new NGLog();
    private static String mstformData = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"BillNo\":\"202210180001\",\"Title\":\"\",\"BillDt\":\"2022-10-18\",\"PlanType\":1,\"PhidPc\":\"169220615000002\",\"SumPlanAmt\":\"\",\"PhidCycle\":\"169220808002002\",\"PhidJsOrg\":\"0\",\"PhidTjOrg\":\"\",\"PhidYsfl\":\"11\",\"Remarks\":\"\",\"PointId\":\"\",\"PhId\":\"\",\"CurOrgId\":\"\",\"PhidSchemeid\":\"758220818000002\",\"NgUpdateDt\":\"\",\"Editor\":\"\",\"WfFlg\":\"\",\"DaFlg\":\"\",\"PhidChkpsn\":\"\",\"ChkDt\":\"\",\"ChkFlg\":\"0\",\"PhidOcode\":\"169220606000002\",\"LevelCode\":\"\",\"NgInsertDt\":\"\",\"PhidActM\":\"\",\"Creator\":\"\",\"PhidTask\":\"\",\"AsrFlg\":\"\",\"key\":\"\"}}}";
    private static String plandgridData = "{\"PhId\":\"-1\",\"Pphid\":\"\",\"NgInsertDt\":null,\"NgUpdateDt\":null,\"NgRecordVer\":0,\"Creator\":\"\",\"Editor\":\"\",\"CurOrgId\":\"\",\"ImpInfo\":\"\",\"PhidBoq\":\"\",\"Cno\":\"202210180003\",\"CzName\":\"\",\"BoqMtype\":0,\"PhidMsunit\":\"\",\"ItemNo\":\"\",\"ItemName\":\"\",\"Rflag\":\"\",\"Ysdj\":10,\"PlanQty\":1,\"PlanQtyScale\":0,\"PlanAmt\":10,\"NexplanQty\":0,\"NexplanQtyScale\":0,\"BoqmQty\":0,\"NexplanAmt\":0,\"Qty\":0,\"Prc\":0,\"PhidActM\":\"\",\"Ftype\":\"\",\"PhidWbs\":\"\",\"PhidWbs_EXName\":\"\",\"PhidCbs\":\"\",\"PhidCbs_EXName\":\"\",\"PhidFbdw\":\"\",\"Htno\":\"\",\"DataFrom\":\"0\",\"DataFrom_EXNAME\":\"来源于自由新增\",\"Remarks\":\"\",\"PhidBoqLevel\":\"\",\"PhidBoqLevel_EXName\":\"\",\"Character\":\"\",\"UnitName\":\"\",\"PhidFbdw_EXName\":\"\",\"PhidPc\":\"\",\"PlanType\":0,\"PhidCyc\":\"\",\"PlanQtyT\":0,\"PlanQtyT2\":0,\"key\":null}";
    private static String mstformData2 = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"BillNo\":\"202210180001\",\"Title\":\"\",\"BillDt\":\"2022-10-18\",\"PlanType\":3,\"PhidPc\":\"169220615000002\",\"SumPlanAmt\":\"\",\"PhidCycle\":\"169220808000002\",\"PhidJsOrg\":\"0\",\"PhidTjOrg\":\"\",\"PhidYsfl\":\"11\",\"Remarks\":\"\",\"PlanBegin\":\"2022-08-01\",\"PlanEnd\":\"2022-08-31\",\"PointId\":\"\",\"PhId\":\"\",\"CurOrgId\":\"\",\"PhidSchemeid\":\"169220808002001\",\"NgUpdateDt\":\"\",\"Editor\":\"\",\"WfFlg\":\"\",\"DaFlg\":\"\",\"PhidChkpsn\":\"\",\"ChkDt\":\"\",\"ChkFlg\":\"0\",\"PhidOcode\":\"169220606000002\",\"LevelCode\":\"\",\"NgInsertDt\":\"\",\"PhidActM\":\"\",\"Creator\":\"\",\"PhidTask\":\"\",\"AsrFlg\":\"\",\"key\":\"\"}}}";
    private static String plandgridData2 = "{\"PhId\":\"-1\",\"Pphid\":\"\",\"NgInsertDt\":null,\"NgUpdateDt\":null,\"NgRecordVer\":0,\"Creator\":\"\",\"Editor\":\"\",\"CurOrgId\":\"\",\"ImpInfo\":\"\",\"PhidBoq\":\"\",\"Cno\":\"202210180001\",\"CzName\":\"\",\"BoqMtype\":0,\"PhidMsunit\":\"\",\"ItemNo\":\"\",\"ItemName\":\"\",\"Rflag\":\"\",\"Ysdj\":10,\"PlanQty\":1,\"PlanQtyScale\":0,\"PlanAmt\":10,\"NexplanQty\":0,\"NexplanQtyScale\":0,\"BoqmQty\":0,\"NexplanAmt\":0,\"Qty\":0,\"Prc\":0,\"PhidActM\":\"\",\"Ftype\":\"\",\"PhidWbs\":\"\",\"PhidWbs_EXName\":\"\",\"PhidCbs\":\"\",\"PhidCbs_EXName\":\"\",\"PhidFbdw\":\"\",\"Htno\":\"\",\"DataFrom\":\"0\",\"DataFrom_EXNAME\":\"来源于自由新增\",\"Remarks\":\"\",\"PhidBoqLevel\":\"\",\"PhidBoqLevel_EXName\":\"\",\"Character\":\"\",\"UnitName\":\"\",\"PhidFbdw_EXName\":\"\",\"PhidPc\":\"\",\"PlanType\":0,\"PhidCyc\":\"\",\"PlanQtyT\":0,\"PlanQtyT2\":0,\"key\":null}";
    @Resource
    private I8Request i8Request;

    /**
     * 对应i8年月度产值
     *
     * @param data
     * @param orgId
     * @return
     */
    @Override
    public I8ReturnModel save(StatAmount data, String orgId) {
        String PhidPc = GetPhIdByCode("project_table", "user_mcxmid", orgId);//pcNo
        try {
            HashMap map = new HashMap<>();
            map.put("PhidPc", PhidPc);
            map.put("SumPlanAmt", data.getYear().getPlanAmount());
            map.put("BillDt", TimeUtils.getDay(new Date()));

            ArrayList<HashMap<String, Object>> detail = new ArrayList<>();
            HashMap grid = new HashMap<>();
            grid.put("PlanAmt", data.getYear().getPlanAmount());
            grid.put("Ysdj", data.getYear().getPlanAmount());
            detail.add(grid);

            List<NameValuePair> formdata = new ArrayList<>();
            formdata.add(new BasicNameValuePair("mstformData", I8Converter.SetField(mstformData, map)));
            formdata.add(new BasicNameValuePair("plandgridData", I8Converter.SetTableRow(plandgridData2, detail)));
            formdata.add(new BasicNameValuePair("plantgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("plantype", "1"));
            formdata.add(new BasicNameValuePair("bustype", "CZ_PLAN_M1"));
            formdata.add(new BasicNameValuePair("isContinue", "false"));
            formdata.add(new BasicNameValuePair("attchmentGuid", "0"));
            formdata.add(new BasicNameValuePair("ng3_logid", "0"));
            I8ReturnModel<String> res = i8Request.PostFormSyncByOcode("/PMS/PMS/CzPlanM/save", formdata, "101");
            if(res.getIsOk()){
                return I8ReturnModel.success();
            }
            throw new RuntimeException(res.getMessage());
        } catch (Exception ex) {
            ngLog.error("ProjectSubcontractsImpl", "分包合同保存异常", ex.getMessage());
            //return I8ReturnModel.error(ex.getMessage());
        }

        try {
            HashMap map = new HashMap<>();
            map.put("PhidPc", PhidPc);
            map.put("SumPlanAmt", data.getMonth().getPlanAmount());
            map.put("BillDt", TimeUtils.getDay(new Date()));

            ArrayList<HashMap<String, Object>> detail = new ArrayList<>();
            HashMap grid = new HashMap<>();
            grid.put("PlanAmt", data.getMonth().getPlanAmount());
            grid.put("Ysdj", data.getMonth().getPlanAmount());
            detail.add(grid);

            List<NameValuePair> formdata = new ArrayList<>();
            formdata.add(new BasicNameValuePair("mstformData", I8Converter.SetField(mstformData2, map)));
            formdata.add(new BasicNameValuePair("plandgridData", I8Converter.SetTableRow(plandgridData2, detail)));
            formdata.add(new BasicNameValuePair("plantgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("plantype", "3"));
            formdata.add(new BasicNameValuePair("bustype", "CZ_PLAN_M3"));
            formdata.add(new BasicNameValuePair("isContinue", "false"));
            formdata.add(new BasicNameValuePair("attchmentGuid", "0"));
            formdata.add(new BasicNameValuePair("ng3_logid", "0"));
            I8ReturnModel<String> res = i8Request.PostFormSyncByOcode("/PMS/PMS/CzPlanM/save", formdata, "101");
            if (res.getIsOk()){
                return I8ReturnModel.success();
            }
            throw new RuntimeException(res.getMessage());
        } catch (Exception ex) {
            ngLog.error("ProjectSubcontractsImpl", "分包合同保存异常", ex.getMessage());
            return I8ReturnModel.error(ex.getMessage());
        }
    }

    @Override
    public StatAmount getData(String orgId) {
        //组织机构id
        //        String orgId = "";
        //从第N条开始
        Integer offset = 0;
        //限制条数
        Integer limit = 100;
        //本次请求所要获取的增量数据的version起始值，客户端需要存储接口返回的数据集合中最后一条数据version值
        Long version = 0L;
        while (true) {
            try {
                Integer year = 2022;
                Integer month = 10;
                String apiUrl = String.format(pcrApi, offset, limit, version, orgId, year, month);
                RequestResult dataBody = client.get(apiUrl);
                String content = dataBody.getContent();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                return JSON.parseObject(content, StatAmount.class);
            } catch (Exception ex) {
                logger.info(String.format("call api error:  %s", ex.getMessage()), ex);
                break;
            }
        }
        return null;
    }

    @Override
    public I8ReturnModel getDataByOrgId(String orgId) {
        return I8ReturnModel.success("获取数据成功", getData(orgId));
    }

    @Override
    public I8ReturnModel saveDataByOrgId(String orgId) {
        StatAmount data = getData(orgId);
        if (data != null) {
            save(data, orgId);
        } else {
            return I8ReturnModel.success(orgId + "-项目，未获取的需要同步的数据");
        }
        return I8ReturnModel.success();
    }
}
